package com.king.web.browser.system.role;

import com.king.mapper.RoleMapper;
import com.king.pojo.dto.RoleDTO;
import com.king.pojo.entity.SysRole;
import com.king.pojo.query.RoleQuery;
import com.king.pojo.vo.AjaxResult;
import com.king.pojo.vo.RoleQueryVo;
import com.king.service.RoleService;
import com.king.web.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色控制器
 *
 * @author liukai
 */
@RestController
@RequestMapping("/system/role")
public class RoleController extends BasicController {

    private final String VIEW_PREFIX = "system/role/";

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMapper roleMapper;

    @GetMapping("/query")
    public AjaxResult query(RoleQuery roleQuery, @PageableDefault Pageable pageable) {
        Map<String, Object> map = new HashMap<>(3);
        Page<SysRole> roleList = roleService.listRole(roleQuery, pageable);
        List<RoleQueryVo> content = roleMapper.roleListToQueryVO(roleList.getContent());
        map.put("content", content);
        map.put("totalElements", roleList.getTotalElements());
        map.put("totalPages", roleList.getTotalPages());
        return success(map);
    }

    @PostMapping("/create")
    public AjaxResult create(@Valid RoleDTO roleDto) {
        SysRole role = roleMapper.roleDtoToRole(roleDto);
        roleService.insert(role);
        return success();
    }

    @GetMapping
    public ModelAndView index() {
        return new ModelAndView(VIEW_PREFIX + "list");
    }

    @GetMapping("/new")
    public ModelAndView insert() {
        return new ModelAndView(VIEW_PREFIX + "new");
    }

}
